(function ($) {
  "use strict";

    //同步订单进度条
    function startRequest(){
        //var x = parseInt(Math.random()*100);
        //$("#synchronousOrderBar .progress-bar").css('width',x+'%');
        //$("#synchronousOrderBar .progress-bar").text(x+'%');
        var total = parseInt($('#totalTask').val());
        //console.log(total);
        if(total>0){
            $.getJSON('/erp/api/importOrder/',function(result){
            //console.log(result);
            //var percent = 100-parseInt((total-parseInt(result.leftCount))/total);
            var percent = ((1-parseInt(result.leftCount)/total)*100).toFixed(2);
            //console.log(percent);
            $("#synchronousOrderBar .progress-bar").css('width',percent+'%');
            $("#synchronousOrderBar .progress-bar").text(percent+'% （'+result.leftCount+' / '+total+'）');

            if(result.isComplete){
                console.log('任务执行完毕！');
                clearInterval();
                $('#synchronousOrderBar').fadeOut(3000);
                $('#totalTask').val(0);
                return false
            }

        });
        }

    }

    //加载订单列表
    function loadOrderList(){

        $("#orderList").block({
                        message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
                        css: {
                            border: "none",
                            backgroundColor: "transparent",
                            color: "#fff",
                            padding: "30px",
                            width: "100%"
                        },
                        timeout: 2e3
                    });

        var parmas = '';

        var store = $('#filterStore').val();
        var country = $('#filterCountry').val();

        var startDate = $('#filterStartDate').val();
        var endDate = $('#filterEndDate').val();

        var pageSize = $('#pageSize').val();
        var pageNo = $('#pageNo').val();

        var status = $('#orderStatus').val();
        var send = $('#orderSend').val();
        var orderMsg = $('#orderMsg').val();

        var addressCheck = $('#addressCheck').val();
        var declareCheck = $('#declareCheck').val();
        var isOutOfStock = $('#isOutOfStock').val();
        var noMatchingSku = $('#noMatchingSku').val();
        var isCanMergeOrder = $('#isCanMergeOrder').val();
        var isShelve = $('#isShelve').val();
        
        var orderPage = $('#orderPage').val();


        parmas +='?store='+store;
        parmas +='&country='+country;
        parmas +='&startDate='+startDate;
        parmas +='&endDate='+endDate;
        parmas +='&pageSize='+pageSize;
        parmas +='&pageNo='+pageNo;
        parmas +='&status='+status;
        parmas +='&send='+send;
        parmas +='&orderMsg='+orderMsg;

        if(typeof(addressCheck)!="undefined"){
            parmas += '&addressCheck=0';
        }
        if(typeof(declareCheck)!="undefined"){
            parmas += '&declareCheck=0';
        }
        if(typeof(isOutOfStock)!="undefined"){
            parmas += '&isOutOfStock=1';
        }
        if(typeof(noMatchingSku)!="undefined"){
            parmas += '&noMatchingSku=1';
        }
        if(typeof(isCanMergeOrder)!="undefined"){
            parmas += '&isCanMergeOrder=1';
        }
        if(typeof(isShelve)!="undefined"){
            parmas += '&isShelve=1';
        }



        $.getJSON("/erp/api/getOrderList"+parmas,function(data){
            var result = data["OrderList"];
            //console.log(result.length);
            if(result.length>0){
                $('#OrderListBox').html('');
                $('#pageItem').html('');
                $.each(result,function(idx,order){
                    var line = '';
                    line += '<tr data-val="'+order["orderId"]+'" data-buyer="'+order['buyerName']+'|'+order['buyerId']+'" data-productCount="'+order["productCount"]+'">';
                    line += '<td><label class="md-check m-a-0"><input type="checkbox" name="post[]" id="ck-'+order["orderId"]+'"><i class="green"></i></label></td>';
                    line += '<td><a href="javascript:" class="orderItem text-primary">'+order["orderId"]+'</a><br>';

                    if(order['isMultiplePackage']){
                        line += '<a class="label purple text-white">拆</a> ';
                    }
                    if(order["memo"].length>0 && order["memo"]!='None'){
                        line += '<a class="label blue text-white showMsg" title="'+order["memo"]+'" data-translate="'+order["memoTranslate"]+'">言</a>';
                    }

                    if(order["productCount"] != '1'){
                        line += ' <span class="label danger text-white">'+order["productCount"]+'件</span> ';
                    }
                    if(order['orderMemo'].length>0){
                        $.each(order['orderMemo'],function(i,memo){
                            if(memo['type']==1){
                                line += ' <a href="javascript:" class="label success text-white orderMemo showMemo" data-type="'+memo['type']+'">拣</a> ';
                            }else if(memo['type']==2){
                                line += ' <a href="javascript:" class="label warn text-white orderMemo showMemo" data-type="'+memo['type']+'">备</a> ';
                            }
                        });
                    }

                    line += '<span class="clearfix p-t-1 separator"></span>';
                    $.each(order['imgList'],function(i,imgObj){
                        var imgSrc = '';
                        if(imgObj['img'].length>0){
                            imgSrc += imgObj['img'];
                        }else{
                            imgSrc += '/static/aside/images/nopic.png';
                        }

                        line += '<a href="javascript:;" data-productId="'+imgObj['productId']+'" class="preview" data-src="'+imgSrc+'">';
                        line += '<img src="'+imgSrc+'" data-src="'+imgSrc+'" class="w-32 img-responsive" style="margin-top: 3px;" alt="'+imgObj['productId']+'"/></a> ';
                    });

                    line += '</td>'
                    line += '<td data-val="'+order["orderCurrency"]+'">$ '+order["orderAmount"]+'</td>';
                    line += '<td> - </td>';
                    line += '<td data-val="'+order["countryCode"]+'">'+order["country"]+'</td>';
                    line += '<td>下单：'+order["orderTime"]+'<br>';
                    //console.log(order["payTime"]);
                    if(order["payTime"] != 'None'  && order['payTime'] != ''){
                        line += '付款：'+order["payTime"]+'<br>';
                        if(order['sendTime'] != 'None' && order['sendTime'] != ''){
                            line += '发货：'+order['sendTime']+'<br>';
                        }else{
                            line += '<span>剩余:</span><code id="leftTime-'+order["orderId"]+'" ></code>';
                            line += '<script>addTimer("leftTime-'+order["orderId"]+'", "'+order["leftTime"]+'");</script>';
                        }

                    }
                    line += '</td><td>';
                    var actionTxt = '';
                    if(order['logisticsData'].sendLogistics.count>0){
                        line += order['logisticsData'].sendLogistics.Logistics[0]['logisticsServiceName'];
                        line += '<br>';
                        $.each(order['logisticsData'].sendLogistics.Logistics,function(i,logistics){
                            line += '[<a href="javascript:void(0)" class="text-info" onclick="doTrack(\''+logistics["logisticsNo"]+'\',\''+idx+'-'+i+'\')">'+logistics["logisticsNo"]+'</a>] <div id="TRNum-'+idx+'-'+i+'"></div>';
                        });
                        actionTxt +='<div class="btn-group dropdown"><a class="text-info dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-print"></i> 打印面单</a>';
                        actionTxt +='<div class="dropdown-menu dropdown-menu-scale pull-right" data-val="'+order['orderId']+'">';
                        actionTxt +='<a class="dropdown-item printMb" href="#">A4L</a><a class="dropdown-item printMb" href="#">A4LI</a><a class="dropdown-item printMb" href="#">A4LC</a><a class="dropdown-item printMb" href="#">A4LCI</a>';
                        actionTxt +='<a class="dropdown-item printMb" href="#">A6L</a><a class="dropdown-item printMb" href="#">A6LI</a><a class="dropdown-item printMb" href="#">A6LC</a><a class="dropdown-item printMb" href="#">A6LCI</a>';
                        actionTxt +='<a class="dropdown-item printMb" href="#">A10x10L</a><a class="dropdown-item printMb" href="#">A10x10LI</a>';
                        actionTxt +='</div></div> <br>';
                        actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';
                    }else{
                        if(order['logisticsData'].deliveryLogistics.count>0){
                            //console.log('已经在系统发货，读取发货物流');
                            line += order['logisticsData'].deliveryLogistics.Logistics[0]['channel'];
                            line += '<br>';
                            $.each(order['logisticsData'].deliveryLogistics.Logistics,function(i,logistics){
                                line += '[<a href="javascript:void(0)" class="text-info" onclick="doTrack(\''+logistics["logicstics_no"]+'\',\''+idx+'-'+i+'\')">'+logistics["logicstics_no"]+'</a>] <div id="TRNum-'+idx+'-'+i+'"></div>';
                            });
                            actionTxt +='<div class="btn-group dropdown"><a class="text-info dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-print"></i> 打印面单</a>';
                            actionTxt +='<div class="dropdown-menu dropdown-menu-scale pull-right" data-val="'+order['orderId']+'">';
                            actionTxt +='<a class="dropdown-item printMb" href="#">A4L</a><a class="dropdown-item printMb" href="#">A4LI</a><a class="dropdown-item printMb" href="#">A4LC</a><a class="dropdown-item printMb" href="#">A4LCI</a>';
                            actionTxt +='<a class="dropdown-item printMb" href="#">A6L</a><a class="dropdown-item printMb" href="#">A6LI</a><a class="dropdown-item printMb" href="#">A6LC</a><a class="dropdown-item printMb" href="#">A6LCI</a>';
                            actionTxt +='<a class="dropdown-item printMb" href="#">A10x10L</a><a class="dropdown-item printMb" href="#">A10x10LI</a>';
                            actionTxt +='</div></div><br>';
                            actionTxt +='<a class="text-info tooltips sendGoodsBtn"><i class="fa fa-send"></i> 发货</a> <br>';
                            actionTxt +='<a class="text-info tooltips orderMemo" data-toggle="modal" data-target="#modal-memo"><i class="fa fa-flag"></i> 备注订单</a> <br>';
                            actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';


                        }else{
                            if(order['logisticsData'].chooseLogistics.count>0){
                                line += order['logisticsData'].chooseLogistics.Logistics[0]['channel'];
                                actionTxt +='<a class="text-info tooltips applyLogisticsNo"><i class="fa fa-cloud-upload"></i> 申请单号</a> <br>';
                                actionTxt +='<a class="text-info tooltips orderMemo" data-toggle="modal" data-target="#modal-memo"><i class="fa fa-flag"></i> 备注订单</a> <br>';
                                actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';
                            }else{
                                line += '物流方式未选择';
                                line += '<br>「<a href="javascript:" class="text-danger showOrderDetail">请选择物流方式</a>」';
                                actionTxt +='<a class="text-info tooltips showOrderDetail"><i class="fa fa-filter"></i> 选择物流</a> <br>';
                                actionTxt +='<a class="text-info tooltips orderMemo" data-toggle="modal" data-target="#modal-memo"><i class="fa fa-flag"></i> 备注订单</a> <br>';
                                actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';
                            }
                        }
                    }

                    line += '</td>';
                    line += '<td>'+order["orderStatus"]+'</td>';
                    line += '<td>'+order["seller"]+'</td>';
                    line += '<td>';
                    line += actionTxt;
                    line += '</td>';
                    line +='</tr>';
                    $('#OrderListBox').append(line);


                });
                $('#pageTxt').html(data["PageTxt"]);
                $('#pageItem').html(data["PageItem"]);
            }else{
                alert('没有数据');
                return false
            }

            $('#pageItem').html(data["PageItem"]);



    });
    }

    $(document).on('click', '#showSide', function() {
        $("#aside").toggleClass("folded");
        $(".app-header .navbar").toggleClass("container");
    });

    $(document).on('click', '#filterBtn', function() {
        //console.log('展开');
        $('#filterBox').toggle();
    });

    $(document).on('click', '.setOffline', function() {
        $('#offlineProductID').val($(this).parent().parent().attr('data-val'));
        $('#offlineProductName').html($(this).parent().parent().attr('data-val'));
    });

    $(document).on('click','#action-toggle',function(){
        if(this.checked){
            $("input[name='post[]']").each(function(){
                this.checked = true;
            });
        }else{
            $("input[name='post[]']").each(function(){
                this.checked = false;
            });
        }
    });

    $(document).on('click', '.editCompany', function() {
        var obj = $(this).parent().parent();
        $('#companyID').val($(this).attr('data-val'));
        $('#editCompanyName').val(obj.children('td').eq(1).children('a').html());
        $('#editManager').val(obj.children('td').eq(2).html());
        $('#editContent').val(obj.children('td').eq(3).html());
    });

    $(document).on('click', '.editPermission', function() {
        var obj = $(this).parent().parent();
        $('#editPermissionID').val($(this).attr('data-val'));
        $('#editPermissionName').val(obj.children('td').eq(1).html());
        $('#editPermissionCodeName').val(obj.children('td').eq(2).html());
        $('#editPermissionContent').val(obj.children('td').eq(3).html());
        if($(this).attr('data-type')!=''){
            $('#editPermissionGroup').val($(this).attr('data-type'));
        }
    });

    $(document).on('click', '.deleteCompany', function() {
      $('#deleteCompanyID').val($(this).attr('data-val'));
        $('#deleteCompanyName').html($(this).parent().parent().children('td').eq(1).children('a').html());
    });

    $(document).on('click', '.deletePermission', function() {
      $('#deletePermissionID').val($(this).attr('data-val'));
        $('#deletePermissionName').html($(this).parent().parent().children('td').eq(1).html());
    });

    $(document).on('click', '.addStore', function() {
      $('#addStoreCompanyID').val($(this).attr('data-val'));
        var obj = $(this).parent().parent();
        $('#storeCompanyName').val(obj.children('td').eq(1).children('a').html());
    });

    $(document).on('click', '.editStore', function() {
      var obj = $(this).parent().parent();
        $('#editStoreID').val($(this).attr('data-val'));
        var host = obj.children('td').eq(4).html();
        $('#editStoreHost').val(host.split('<br>')[0]);
        $('#editStoreServiceIP').val(host.split('<br>')[1]);
        $('#editStoreClientID').val(obj.children('td').eq(2).html());
        $('#editStoreAppSecret').val(obj.children('td').eq(5).html());
        $('#editStoreRefreshToken').val(obj.children('td').eq(6).html());
        $('#editStoreAccessToken').val(obj.children('td').eq(7).html());
        $('#editStoreRedirectURL').val(obj.children('td').eq(8).html());
        $('#editStoreType').val(obj.children('td').eq(3).attr('data-val'));
        var companyName = obj.children('td').eq(1).children('a');
        if(companyName.length<=0){
            $('#editStoreCompanyName').val(obj.children('td').eq(1).html());
        }else{
            $('#editStoreCompanyName').val(obj.children('td').eq(1).children('a').html());
        }
    });

    $(document).on('click', '.addUser', function() {
      var storeID = $(this).attr('data-val');
        var obj = $(this).parent().parent();
        $('#addUserStoreID').val(storeID);
        $('#addUserStoreClientID').val(obj.children('td').eq(2).html());
        var companyName = obj.children('td').eq(1).children('a');
        if(companyName.length<=0){
            $('#addUserCompanyName').val(obj.children('td').eq(1).html());
        }else{
            $('#addUserCompanyName').val(obj.children('td').eq(1).children('a').html());
        }


        //$('#multiple').children('optgroup').html('');

         //$.getJSON("{% url 'system:getUserList' %}"+'?storeID='+storeID,function(data){
         $.getJSON("/system/api/getUserList"+'?storeID='+storeID,function(data){

             var result = data["Users"];
             $.each(result,function(idx,user){
                 //console.log(user.username);
                 var line = '';
                 if(user.selected == true){
                     line += '<option selected="selected" value="'+user.username+'">'+user.first_name+'</option>';
                     //$('<li class="select2-selection__choice" title="'+user.first_name+'"><span class="select2-selection__choice__remove" role="presentation">×</span>'+user.first_name+'</li>').insertBefore(".select2-search--inline");
                 }else{
                     line += '<option value="'+user.username+'">'+user.first_name+'</option>';
                 }

                 $('#multiple').children('optgroup').append(line);

             });

         });
    });

    $(document).on('click', '.deleteStore', function() {
      $('#deleteStoreID').val($(this).attr('data-val'));
        $('#deleteStoreClientID').html($(this).parent().parent().children('td').eq(1).html()+'['+$(this).parent().parent().children('td').eq(2).html()+']');
    });

    $(document).on('change', '#selectCompany', function() {
      var id = $(this).val();
        window.location.href = "/system/company/"+id;
    });

    $(document).on('click', '.editUser', function() {
        var uid = $(this).attr('data-val');
        var username = $(this).parent().parent().parent().parent().children().eq(0).children('span').eq(0).attr('data-val');
        var firstname = $(this).parent().parent().parent().children().eq(1).children().eq(0).attr('data-val');
        var email = $(this).parent().parent().parent().children().eq(2).attr('data-val');
        $('#editUserName').val(username);
        $('#editUserFirstName').val(firstname);
        $('#editUserEmail').val(email);
        $('#editUserID').val(uid);
    });

    $(document).on('click', '.deleteUser', function() {
        var uid = $(this).attr('data-val');
        var username = $(this).parent().parent().parent().parent().children().eq(0).children('span').eq(0).attr('data-val');
        $('#deleteUserName').html(username);
        $('#deleteUserID').val(uid);
    });

    $(document).on('click', '.removeGroup', function() {
        var uid = $(this).attr('data-val');
        var gid = $('#addGroupSelect').val();
        var gname = $('#selectedGroupName').val();
        var username = $(this).parent().parent().parent().parent().children().eq(0).children('span').eq(0).attr('data-val');
        $('#removeUserName').html(username);
        $('#removeGroupName').html(gname);
        $('#removeUserID').val(uid);
        $('#removeGroupID').val(gid);
    });

    $(document).on('click', '#editActive', function() {
        $('.permissionItem,#savePermission').removeAttr('disabled');
    });

    $(document).on('click', '#savePermission', function() {
        $('.permissionItem,#savePermission').attr('disabled','disabled');
        //var obj = $('input.permissionItem:checked');
        var gid = $('#selectedGroupID').val();
        var uid = $('#selectedUserID').val();
        var selectedPerm = '';
        $('input.permissionItem:checked').each(function(){
            //console.log($(this).val());
            selectedPerm +=$(this).val();
            selectedPerm +=',';

        });
        console.log(selectedPerm);

        var type = $('#editPermissionType').val();

        var url = '/system/api/savePermission';
        if(type=='user'){
            $.post(url,{uid:uid,perms:selectedPerm},function(result){
                if(result.error){
                    alert(result.msg);
                }else{
                    alert('保存用户权限成功！');
                }
            });

        }else if(type=='group'){
            $.post(url,{gid:gid,perms:selectedPerm},function(result){
                if(result.error){
                    alert(result.msg);
                }else{
                    alert('保存用户组权限成功！');
                }
            });
        }else{
            alert('保存权限失败！');
        }
    });


    $(document).on('click', '.editStock', function() {
        var productId = $(this).parent().parent().attr('data-val');
        var store_id = $(this).parent().parent().attr('data-store');
        $('#editStockProductId').val(productId);
        $('#editStockStoreId').val(store_id);
        $.getJSON("/erp/api/getProductSku"+'?productId='+productId,function(data){
            //console.log(data);
            var editStockItems = $('#editStockItems');
            editStockItems.html('');
            var html = '';
            if(data.items >1){
                var result = data["skuList"];
                //console.log(result);
                $.each(result,function(idx,sku){

                    var skuname = '';
                    //var skuimage = '';

                    if(sku["skuName"]=='None'){
                        skuname += sku["skuId"];
                    }else{
                        skuname += sku["skuName"];
                    }

                    html +='<div class="form-group row"><label for="skuItem" class="col-sm-7 form-control-label">'+skuname+'：</label><div class="col-sm-5">';
                    html += '<input class="form-control stockItem" type="text" name="'+sku["skuId"]+'" value="'+sku["ipmSkuStock"]+'"></div></div>';
                });

                html +='<p>总库存:<code>'+data.totalStock+'</code></p>';

            }else{
                //console.log(data);
                html += '<div class="form-group row"><label for="allStock" class="col-sm-4 form-control-label">总库存：</label><div class="col-sm-8">';
                html += '<input class="form-control" type="text" name="'+data.skuId+'" value="'+data.ipmSkuStock+'"></div></div>';
            }

            editStockItems.append(html);

        });
    });

    $(document).on('click', '#editStockBtn', function() {
        var productId = $('#editStockProductId').val();
        var store_id = $('#editStockStoreId').val();
        var obj = $('#editStockItems input');
        var url = "/erp/api/smtAPI";
        url +='?_api_=editSingleSkuStock';
        url +='&store_id='+store_id;
        url +='&productId='+productId;
        for(var i=0; i<obj.length; i++){
            var skuId = obj[i].name;
            var stock = obj[i].value;
            $.get(url+'&skuId='+skuId+'&stock='+stock, function(result){
                console.log('库存已经更新');
            });
          }

        alert('库存已更新！');
        $.get('/erp/api/getProductStock?productId='+productId, function(result){
                if(result.error){
                    alert(result.msg)
                }else{
                    $('#stock-'+productId).html(result.stock);
                }
            });
        $('#modal-editStock').modal('hide');

    });

    $(document).on('click', '.editPrice', function() {
        var productId = $(this).parent().parent().attr('data-val');
        var store_id = $(this).parent().parent().attr('data-store');
        $('#editPriceProductId').val(productId);
        $('#editPriceStoreId').val(store_id);
        $.getJSON("/erp/api/getProductSku"+'?productId='+productId,function(data){
            //console.log(data);
            var editPriceItems = $('#editPriceItems');
            editPriceItems.html('');
            var html = '';
            if(data.items >1){
                var result = data["skuList"];
                $.each(result,function(idx,sku){

                    var skuname = '';

                    if(sku["skuName"]=='None'){
                        skuname += sku["skuId"];
                    }else{
                        skuname += sku["skuName"];
                    }

                    html +='<div class="form-group row"><label for="skuItem" class="col-sm-7 form-control-label">'+skuname+'：</label><div class="col-sm-5">';
                    html += '<input class="form-control priceItem" type="text" name="'+sku["skuId"]+'" value="'+sku["skuPrice"]+'"></div></div>';
                });

            }else{
                html += '<div class="form-group row"><label for="allStock" class="col-sm-4 form-control-label">价格：</label><div class="col-sm-8">';
                html += '<input class="form-control" type="text" name="'+data.skuId+'" value="'+data.skuPrice+'"></div></div>';
            }

            editPriceItems.append(html);
        });

    });

    $(document).on('click', '.editBulkPrice', function() {
        var productId = $(this).parent().parent().attr('data-val');
        var store_id = $(this).parent().parent().attr('data-store');
        var bulkData = $(this).attr('data-attr');
        $('#editBulkPriceStoreId').val(store_id);
        $('#editBulkOrder').val(bulkData.split('|')[0]);
        $('#editBulkDiscount').val(bulkData.split('|')[1]);
        $('#editBulkDiscountRate').html((100-parseInt(bulkData.split('|')[1]))/10);
    });

    $(document).on('keyup', '#editBulkDiscount', function() {
      $('#editBulkDiscountRate').html((100-parseInt($('#editBulkDiscount').val()))/10);
    });

    $(document).on('click', '.editSubject', function() {
        var productId = $(this).parent().parent().attr('data-val');
        var store_id = $(this).parent().parent().attr('data-store');
        $('#editSubjectStoreId').val(store_id);
        $('#editSubjectProductId').val(productId);
        $('#editSubjectEn').val($(this).parent().children().eq(0).text());
    });

    $(document).on('keyup', '#editSubjectEn', function() {
        $('.showCount').css('display','block');
        var count = $(this).val().length;
        $('#countNum').html(count);
        if(count>218){
            alert('仅能输入218个字符！');
        }
    });

    $(document).on('click', '#editSubjectBtn', function() {
        var stote_id = $('#editSubjectStoreId').val();
        var productId = $('#editSubjectProductId').val();
        var fiedName = 'subject';
        var fiedvalue = $('#editSubjectEn').val();
        var url = "/erp/api/smtAPI";
        if(productId=='0'){
            alert('产品ID有误！');
            return false;
        }

        if(fiedvalue.length<=0){
            alert('标题不能为空！');
            return false;
        }
        else{
            url +='?_api_=editSimpleProductFiled';
            url +='&stote_id='+stote_id;
            url +='&productId='+productId;
            url +='&fiedName='+fiedName;
            url +='&fiedvalue='+fiedvalue;
            //console.log(url);
            $.get(url, function(result){
                //console.log(result);
                if(result.error){
                    alert(result.msg)
                }else{
                    $('#sub-'+productId).html(fiedvalue);
                    alert('产品标题已经更新！');
                    $('#modal-editSubject').modal('hide');
                }
            });
        }
    });

    $(document).on('blur', '#editSubjectEn', function() {
      $('.showCount').css('display','none');
    });

    $(document).on('click', '.renewExpire', function() {
        var productId = $(this).parent().parent().attr('data-val');
        var storeId = $(this).parent().parent().attr('data-store');
        var url = "/erp/api/smtAPI";
        url +='?_api_=renewExpire';
        url +='&store_id='+storeId;
        url +='&productId='+productId;
        //console.log(url);
        $.get(url, function(result){
            //console.log(result);
            if(result.error){
                alert(result.msg)
            }else{
                alert('产品有效期已经更新！');
            }

          });
    });

    $(document).on('click', '.setSearchType', function() {
        $('#searchType').val($(this).attr('data-val'));
        $('#searchTypeText').html($(this).text());
    });

    //客服处理页面
    $(document).on('click', '#show-en', function() {
      $('.msg-en').toggle();
    });

    $(document).on('click', '#mark-read', function() {
      alert('标记成功！');
    });

    $(document).on('click', '#showQuick', function() {
        $('#quickReplay').toggle();
        $('#m-list').toggle();
    });

    //运费计算页面
    $(document).on('keyup', '.inputNumber', function() {
      $(this).val($(this).val().replace(/[^\d]/g,''));
    });

    $(document).on('keyup', '.inputPrice', function() {
      $(this).val($(this).val().replace(/[^\d|.]/g,''));
    });

    $(document).on('click', '#searchExpress', function() {
        var weight = $('#Pweight').val();
        var length = $('#Plength').val();
        var width = $('#Pwidth').val();
        var height = $('#Pheight').val();
        var country = $('#country').val();
        var selectProductID = $('#selectProductID').val();
        var isHandian = $('#isHandian').val();
        var jinghuojia = $('#Pjinghuojia').val();
        var profit = $('#Pprofit').val();

        var url = "/erp/api/logisticsAPI";
        url += "?_api_=calculate";

        if(weight.length<=0 || parseInt(weight)<=0){
            alert('重量必填且大于0！');
            return false
        }else{
            url +='&weight='+weight;
        }

        if(country.length<=0){
            alert('国家必选！');
        }else{
            url +='&country='+country;
        }

        if(length.length>0 && parseInt(length)>0){
            url +='&lengths='+length;
        }
        if(width.length>0 && parseInt(width)>0){
            url +='&widths='+width;
        }
        if(height.length>0 && parseInt(height)>0){
            url +='&heights='+height;
        }
        url += '&IS_ELECTRIC='+isHandian;

        if(jinghuojia.length>0 && parseFloat(jinghuojia)>0){
            url +='&jinghuojia='+jinghuojia;
        }
        if(profit.length>0 && parseFloat(profit)>0){
            url +='&profit='+profit;
        }

        //console.log(url);


        $.getJSON(url,function(data){
            if(data.error){
                alert(data.msg);
                return false
            }
                var result = data.data.result;
                $('.logistic-fee').html('');
                var html = '';
                $.each(result,function(idx,item){

                    //console.log(item['NAME']);

                    var jipao = '';
                    if(item['JIPAO']==0){
                        jipao +='不计抛';
                    }else{
                        jipao +='计抛';
                    }

                    html += '<tr><td>'+item['TYPE']+'</td>';
                    html += '<td><a class="channelTips" title="'+item['SHORT_NOTE']+'" data-note="'+item['LONG_NOTE']+'">'+item['NAME']+'</a></td>';
                    html += '<td>'+jipao+'</td>';
                    html += '<td>'+item['IS_ELECTRIC']+'</td>';
                    html += '<td>'+item['FEE']+'</td>';
                    html += '<td>'+item['PRICE'].toFixed(2)+'</td>';
                    html += '<td>'+item['SHIXIAO']+'</td>';
                    html += '<td class="remark">成功</td>';
                    html += '</tr>';
                });

                $('.logistic-fee').html(html);

             });

        $('#showLogistics').css('display','block');
    });

    $(document).on('click', '.channelTips', function() {
        var note = $(this).attr('data-note');
        note = note.replace(/\t/g,"");
        note = note.replace(/\r\n/g,"<br>");
        $('.logisticsTipsContent').html('<pre class="text-left p-a">'+note+'</pre>');
        $('#logisticsTitle').text($(this).text());
        $('#modal-logisticsTips').modal('show');
    });

    //订单处理页面
    $(document).on('click', '#btnEditOrderAddress', function() {
        $('.orderAddressForm input,.orderAddressForm select, #btnSaveOrderAddress').removeAttr('disabled');
    });
    $(document).on('click', '#btnSaveOrderAddress', function() {
        var contactNmae = $('#contactNmae').val();
        var address1 = $('#address1').val();
        var address2 = $('#address2').val();
        var phone = $('#phone').val();
        var mobile = $('#mobile').val();
        var country = $('#country').val();
        var city = $('#city').val();
        var province = $('#province').val();
        var zipCode = $('#zipCode').val();

        if((contactNmae.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0){
            alert('收件人必填');
            $('#contactNmae').focus();
            return false
        }
        if((address1.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0){
            alert('地址1必填');
            $('#address1').focus();
            return false
        }
        if(country.length==0){
            alert('国家必填');
            $('#country').focus();
            return false
        }
        if((city.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0){
            alert('城市必填');
            $('#city').focus();
            return false
        }
        if((province.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0){
            alert('省/州/地区必填');
            $('#province').focus();
            return false
        }
        if((zipCode.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0){
            alert('邮编必填');
            $('#zipCode').focus();
            return false
        }
        if((phone.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0 && (mobile.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0 ){
            alert('电话或手机必填其中之一');
            $('#phone').focus();
            return false
        }

        var orderId = $('#selectedOrder').val();
        var dd = {orderId:orderId,country:country,city:city,province:province,zip:zipCode,contactPerson:contactNmae,address1:address1,address2:address2,phone:phone,mobile:mobile}

        //console.log(dd);

        $.getJSON('/erp/api/editAddress',dd,function(data){
            if(data.error){
                console.log(data.msg);
            }else{
                $('.deliveryAddress i').removeClass('fa-times text-danger');
                $('.deliveryAddress i').addClass('fa-check text-success');
            }
        });

        $('.orderAddressForm input,.orderAddressForm select, #btnSaveOrderAddress').attr('disabled','disabled');

    });
    //跳转页码
    $(document).on('keydown', '#jumpTo', function() {
        if (event.keyCode == 13) {
            var page = $(this).val();
            if(page.length<=0){
                alert('请填写页码');
                $('#jumpTo').focus();
                return false;
            }else{
                var re = /^[0-9]+.?[0-9]*$/;
                if (!re.test(page)){
                    alert("请输入数字");
                    return false;
                }else{
                    $("#orderList").block({
                        message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
                        css: {
                            border: "none",
                            backgroundColor: "transparent",
                            color: "#fff",
                            padding: "30px",
                            width: "100%"
                        },
                        timeout: 2e3
                    });
                    $('#pageNo').val(page);
                    loadOrderList();
                }

            }
        }
    });
    $(document).on('click', '#btnJump', function() {
        var page = $('#jumpTo').val();
        if(page.length<=0){
            alert('请填写页码');
             $('#jumpTo').focus();
             return false;
        }else{
            var re = /^[0-9]+.?[0-9]*$/;
            if (!re.test(page)){
                alert("请输入数字");
                return false;
            }else{
                $("#orderList").block({
                    message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
                    css: {
                        border: "none",
                        backgroundColor: "transparent",
                        color: "#fff",
                        padding: "30px",
                        width: "100%"
                    },
                    timeout: 2e3
                });
                $('#pageNo').val(page);
                loadOrderList();
            }

        }
    });
    //订单搜索
    $(document).on('click', '#btnSearch', function() {

        $("#orderList").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: {
                border: "none",
                backgroundColor: "transparent",
                color: "#fff",
                padding: "30px",
                width: "100%"
            },
            timeout: 2e3
        });


        var keyword = $('#keyword').val();
        var searchType = $('#searchType').val();
        var status = $('#orderStatus').val();
        var send = $('#orderSend').val();
        var orderMsg = $('#orderMsg').val();

        var addressCheck = $('#addressCheck').val();
        var declareCheck = $('#declareCheck').val();
        var isOutOfStock = $('#isOutOfStock').val();
        var noMatchingSku = $('#noMatchingSku').val();
        var isCanMergeOrder = $('#isCanMergeOrder').val();
        var isShelve = $('#isShelve').val();

        $('#pageNo').val('1');
        if(keyword.length<=0){
             alert('请填写搜索关键词');
             $('#keyword').focus();
             return false;
         }else{


            $('#OrderListBox').html('');
            $('#pageItem').html('');

            var parmas = '';
            parmas +='?searchType='+searchType;
            parmas +='&keyword='+keyword;
            parmas +='&status='+status;
            parmas +='&send='+send;
            parmas +='&orderMsg='+orderMsg;

            if(typeof(addressCheck)!="undefined"){
                parmas += '&addressCheck=0';
            }
            if(typeof(declareCheck)!="undefined"){
                parmas += '&declareCheck=0';
            }
            if(typeof(isOutOfStock)!="undefined"){
                parmas += '&isOutOfStock=1';
            }
            if(typeof(noMatchingSku)!="undefined"){
                parmas += '&noMatchingSku=1';
            }
            if(typeof(isCanMergeOrder)!="undefined"){
                parmas += '&isCanMergeOrder=1';
            }
            if(typeof(isShelve)!="undefined"){
                parmas += '&isShelve=1';
            }



            $.getJSON("/erp/api/getOrderList"+parmas,function(data){
            var result = data["OrderList"];
            $.each(result,function(idx,order){
                var line = '';
                line += '<tr data-val="'+order["orderId"]+'" data-buyer="'+order['buyerName']+'|'+order['buyerId']+'" data-productCount="'+order['productCount']+'">';
                line += '<td><label class="md-check m-a-0"><input type="checkbox" name="post[]" id="ck-'+order["orderId"]+'"><i class="green"></i></label></td>';
                line += '<td><a href="javascript:" class="orderItem text-primary">'+order["orderId"]+'</a><br>';
                if(order['isMultiplePackage']){
                    line += '<a class="label purple text-white">拆</a> ';
                }
                if(order["memo"].length>0 && order["memo"]!='None'){
                    line += '<a class="label blue text-white showMsg" title="'+order["memo"]+'" data-translate="'+order["memoTranslate"]+'">言</a>';
                }
                if(order["productCount"] != '1'){
                    line += ' <span class="label danger text-white">'+order["productCount"]+'件</span> ';
                }
                if(order['orderMemo'].length>0){
                        $.each(order['orderMemo'],function(i,memo){
                            if(memo['type']==1){
                                line += ' <a href="javascript:" class="label success text-white orderMemo showMemo" data-type="'+memo['type']+'">拣</a> ';
                            }else if(memo['type']==2){
                                line += ' <a href="javascript:" class="label warn text-white orderMemo showMemo" data-type="'+memo['type']+'">备</a> ';
                            }
                        });
                    }
                line += '<span class="clearfix p-t-1 separator"></span>';
                    $.each(order['imgList'],function(i,imgObj){
                        var imgSrc = '';
                        if(imgObj['img'].length>0){
                            imgSrc += imgObj['img'];
                        }else{
                            imgSrc += '/static/aside/images/nopic.png';
                        }

                        line += '<a href="javascript:;" data-productId="'+imgObj['productId']+'" class="preview" data-src="'+imgSrc+'">';
                        line += '<img src="'+imgSrc+'" data-src="'+imgSrc+'" class="w-32 img-responsive" style="margin-top: 3px;" alt="'+imgObj['productId']+'"/></a>';
                    });
                line += '</td>'
                line += '<td data-val="'+order["orderCurrency"]+'">$ '+order["orderAmount"]+'</td>';
                line += '<td> - </td>';
                line += '<td data-val="'+order["countryCode"]+'">'+order["country"]+'</td>';
                line += '<td>下单：'+order["orderTime"]+'<br>';
                //console.log(order["payTime"]);
                if(order["payTime"] != 'None' && order['payTime'] != ''){
                    line += '付款：'+order["payTime"]+'<br>';
                    if(order['sendTime'] != 'None' && order['sendTime'] != ''){
                            line += '发货：'+order['sendTime']+'<br>';
                        }else{
                            line += '<span>剩余:</span><code id="leftTime-'+order["orderId"]+'" ></code>';
                            line += '<script>addTimer("leftTime-'+order["orderId"]+'", "'+order["leftTime"]+'");</script>';
                        }
                }

                line += '</td><td>';
                var actionTxt = '';
                if(order['logisticsData'].sendLogistics.count>0){
                    line += order['logisticsData'].sendLogistics.Logistics[0]['logisticsServiceName'];
                    line += '<br>';
                    $.each(order['logisticsData'].sendLogistics.Logistics,function(i,logistics){
                        line += '[<a href="javascript:void(0)" class="text-info" onclick="doTrack(\''+logistics["logisticsNo"]+'\',\''+idx+'-'+i+'\')">'+logistics["logisticsNo"]+'</a>] <div id="TRNum-'+idx+'-'+i+'"></div>';
                    });
                    actionTxt +='<div class="btn-group dropdown"><a class="text-info dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-print"></i> 打印面单</a>';
                    actionTxt +='<div class="dropdown-menu dropdown-menu-scale pull-right" data-val="'+order['orderId']+'">';
                    actionTxt +='<a class="dropdown-item printMb" href="#">A4L</a><a class="dropdown-item printMb" href="#">A4LI</a><a class="dropdown-item printMb" href="#">A4LC</a><a class="dropdown-item printMb" href="#">A4LCI</a>';
                    actionTxt +='<a class="dropdown-item printMb" href="#">A6L</a><a class="dropdown-item printMb" href="#">A6LI</a><a class="dropdown-item printMb" href="#">A6LC</a><a class="dropdown-item printMb" href="#">A6LCI</a>';
                    actionTxt +='<a class="dropdown-item printMb" href="#">A10x10L</a><a class="dropdown-item printMb" href="#">A10x10LI</a>';
                    actionTxt +='</div></div> <br>';
                    actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';
                }else{
                    if(order['logisticsData'].deliveryLogistics.count>0){
                        //console.log('已经在系统发货，读取发货物流');
                        line += order['logisticsData'].deliveryLogistics.Logistics[0]['channel'];
                        line += '<br>';
                        $.each(order['logisticsData'].deliveryLogistics.Logistics,function(i,logistics){
                            line += '[<a href="javascript:void(0)" class="text-info" onclick="doTrack(\''+logistics["logicstics_no"]+'\',\''+idx+'-'+i+'\')">'+logistics["logicstics_no"]+'</a>] <div id="TRNum-'+idx+'-'+i+'"></div>';
                        });
                        actionTxt +='<div class="btn-group dropdown"><a class="text-info dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-print"></i> 打印面单</a>';
                        actionTxt +='<div class="dropdown-menu dropdown-menu-scale pull-right" data-val="'+order['orderId']+'">';
                        actionTxt +='<a class="dropdown-item printMb" href="#">A4L</a><a class="dropdown-item printMb" href="#">A4LI</a><a class="dropdown-item printMb" href="#">A4LC</a><a class="dropdown-item printMb" href="#">A4LCI</a>';
                        actionTxt +='<a class="dropdown-item printMb" href="#">A6L</a><a class="dropdown-item printMb" href="#">A6LI</a><a class="dropdown-item printMb" href="#">A6LC</a><a class="dropdown-item printMb" href="#">A6LCI</a>';
                        actionTxt +='<a class="dropdown-item printMb" href="#">A10x10L</a><a class="dropdown-item printMb" href="#">A10x10LI</a>';
                        actionTxt +='</div></div><br>';
                        actionTxt +='<a class="text-info tooltips sendGoodsBtn"><i class="fa fa-send"></i> 发货</a> <br>';
                        actionTxt +='<a class="text-info tooltips orderMemo" data-toggle="modal" data-target="#modal-memo"><i class="fa fa-flag"></i> 备注订单</a> <br>';
                        actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';


                    }else{
                        if(order['logisticsData'].chooseLogistics.count>0){
                            line += order['logisticsData'].chooseLogistics.Logistics[0]['channel'];
                            actionTxt +='<a class="text-info tooltips applyLogisticsNo"><i class="fa fa-cloud-upload"></i> 申请单号</a> <br>';
                            actionTxt +='<a class="text-info tooltips orderMemo" data-toggle="modal" data-target="#modal-memo"><i class="fa fa-flag"></i> 备注订单</a> <br>';
                            actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';
                        }else{
                            line += '物流方式未选择';
                            line += '<br>「<a href="javascript:" class="text-danger showOrderDetail">请选择物流方式</a>」';
                            actionTxt +='<a class="text-info tooltips showOrderDetail"><i class="fa fa-filter"></i> 选择物流</a> <br>';
                            actionTxt +='<a class="text-info tooltips orderMemo" data-toggle="modal" data-target="#modal-memo"><i class="fa fa-flag"></i> 备注订单</a> <br>';
                            actionTxt +='<a class="text-info tooltips showOrderDetail" data-toggle="modal" data-target="#modal-OrderDetail"><i class="fa fa-eye"></i> 订单详情</a>';
                        }
                    }
                }

                line += '</td>'
                line += '<td>'+order["orderStatus"]+'</td>';
                line += '<td>'+order["seller"]+'</td>';
                line += '<td>';
                line += actionTxt;
                line += '</td>';
                line +='</tr>';
                $('#OrderListBox').append(line);

            });

            $('#pageItem').html(data["PageItem"]);
            $('#pageTxt').html(data["PageTxt"]);


        });
        }
    });
    //每页显示条数
    $(document).on('change', '#selectPageSize', function() {
        $("#orderList").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: {
                border: "none",
                backgroundColor: "transparent",
                color: "#fff",
                padding: "30px",
                width: "100%"
            },
            timeout: 2e3
        });
        var pagesize = $(this).children('option:selected').val();
        $('#pageSize').val(pagesize);
        $('#pageNo').val('1');
        loadOrderList();
    });
    //自定义日期
    $(document).on('click', '#btnDiyDate', function() {
        $("#orderList").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: {
                border: "none",
                backgroundColor: "transparent",
                color: "#fff",
                padding: "30px",
                width: "100%"
            },
            timeout: 2e3
        });
        $('#filterStartDate').val($('#startDate').val());
        $('#filterEndDate').val($('#endDate').val());
        loadOrderList();
    });
    //设置日期
    $(document).on('click', '.setDate', function() {
        $("#orderList").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: {
                border: "none",
                backgroundColor: "transparent",
                color: "#fff",
                padding: "30px",
                width: "100%"
            },
            timeout: 2e3
        });

        $('.setDate').removeClass('orange');
        $(this).addClass('orange');
        var dt = $(this).attr('data-val');
        $('#pageNo').val('1');

        switch(dt){
            case '5':
                $('#modal-DiyDate').modal('show');
                break;
            case '4':
                $('#filterStartDate').val(getFormatDate(29));
                loadOrderList();
                break;
            case '3':
                $('#filterStartDate').val(getFormatDate(6));
                loadOrderList();
                break;
            case '2':
                $('#filterStartDate').val(getFormatDate(1));
                $('#filterEndDate').val(getFormatDate(1));
                loadOrderList();
                break;
            case '1':
                $('#filterStartDate').val(getFormatDate(0));
                loadOrderList();
                break;
            case '0':
                $('#filterStartDate').val(getFormatDate(90));
                loadOrderList();
                break;
            default :
                //日期错误,返回7天
                $('#filterStartDate').val(getFormatDate(6));
                loadOrderList();
            }
    });
    //选中国家
    $(document).on('click', '.setCountry', function() {
        $("#orderList").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: {
                border: "none",
                backgroundColor: "transparent",
                color: "#fff",
                padding: "30px",
                width: "100%"
            },
            timeout: 2e3
        });
        $('.setCountry').removeClass('orange');
        $(this).addClass('orange');
        $('#filterCountry').val($(this).attr('data-val'));
        $('#pageNo').val('1');
        loadOrderList();
    });
    //选中翻页
    $(document).on('click', '.pageItem', function() {
        var page = $(this).attr('data-val');
        if(page != '...'){
            $("#orderList").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: {
                border: "none",
                backgroundColor: "transparent",
                color: "#fff",
                padding: "30px",
                width: "100%"
            },
            timeout: 2e3
        });
            $('#pageNo').val(page);
            loadOrderList();
        }

    });
    //选中店铺
    $(document).on('click', '.setStore', function() {
        $("#orderList").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: {
                border: "none",
                backgroundColor: "transparent",
                color: "#fff",
                padding: "30px",
                width: "100%"
            },
            timeout: 2e3
        });
        $('.setStore').removeClass('orange');
        $(this).addClass('orange');
        $('#filterStore').val($(this).attr('data-val'));
        $('#pageNo').val('1');
        loadOrderList();
    });
    $(document).on('click', '#closeGoodsInfoBox', function() {
        $('#goodsInfoBox').hide();
    });
    //加载订单详情
    $(document).on('click', '.showOrderDetail', function() {
        $('#declareInformation table').show();
        $('#declareInformation #declareForm').remove();
        var orderId = $(this).parent().parent().attr('data-val');
        var orderAmount = $(this).parent().parent().children('td').eq(2).html();
        var orderSeller = $(this).parent().parent().children('td').eq(8).html();
        var buyerInfo = $(this).parent().parent().attr('data-buyer');
        var productCount = $(this).parent().parent().attr('data-productCount');
        $('#selectedLine').val($(this).parent().parent().index());

        $('#selectedOrder').val(orderId);

        $('.orderAddressForm input,.orderAddressForm select').attr('disabled','disabled');

        $('#selectLogisticsChanel').children().eq(0).attr("selected","selected");
        $("#selectLogisticsChanel").select2();

        //$('#selectLogisticsChanel').children().eq(0).attr("selected","selected");
        //$('#select2-selectLogisticsChanel-container').text($('#selectLogisticsChanel').children().eq(0).text());
        //$('#select2-selectLogisticsChanel-container').attr("title","-----请选择物流方式-----");

        $('.getNoMethod button').hide();


        $.getJSON("/erp/api/getOrderDealMark?orderId="+orderId,function(data){
            if(data.error){
                console.log(data.msg);
            }else{

                var ac = data.result.address_check;
                var dc = data.result.declare_check;
                var slt = data.result.select_logicstics_time;
                var sgt = data.result.send_goods_time;
                var vdt = data.result.virtual_delivery_time;
                var alnt = data.result.apply_logicstics_no_time;
                var plt = data.result.print_logicstics_time;



                if(sgt!= null && sgt != 'None'){
                    $('.orderIsSend,.orderIsPrint,.orderIsPick,.orderIsApply,.orderIsDeal').removeClass('grey-300');
                    $('.orderIsSend,.orderIsPrint,.orderIsPick,.orderIsApply,.orderIsDeal').addClass('success');
                }else{
                    $('.orderIsSend,.orderIsPrint,.orderIsPick,.orderIsApply,.orderIsDeal').removeClass('success');
                    $('.orderIsSend,.orderIsPrint,.orderIsPick,.orderIsApply,.orderIsDeal').addClass('grey-300');
                }

                if((slt!=null && slt != 'None') || (sgt!= null && sgt != 'None') || (vdt != null && vdt != 'None') || (alnt !=null && alnt != 'None') || (plt!=null && plt != 'None') ){
                    $('.logisticsInformation i').removeClass('fa-times text-danger');
                    $('.logisticsInformation i').addClass('fa-check text-success');
                }else{
                    $('.logisticsInformation i').removeClass('fa-check text-success');
                    $('.logisticsInformation i').addClass('fa-times text-danger');

                    $('.commentInformation a').removeClass('active');
                    $('.deliveryAddress a').removeClass('active');
                    $('.customsInformation a').removeClass('active');
                    $('.logisticsInformation a').addClass('active');
                    $('#commentInformation').removeClass('active').attr('aria-expanded','false');
                    $('#deliveryAddress').removeClass('active').attr('aria-expanded','false');
                    $('#customsInformation').removeClass('active').attr('aria-expanded','false');
                    $('#logisticsInformation').addClass('active').attr('aria-expanded','true');
                }
                if(dc){
                    $('.customsInformation i').removeClass('fa-times text-danger');
                    $('.customsInformation i').addClass('fa-check text-success');
                }else{
                    $('.customsInformation i').removeClass('fa-check text-success');
                    $('.customsInformation i').addClass('fa-times text-danger');

                    $('.commentInformation a').removeClass('active');
                    $('.deliveryAddress a').removeClass('active');
                    $('.logisticsInformation a').removeClass('active');
                    $('.customsInformation a').addClass('active');

                    $('#commentInformation').removeClass('active').attr('aria-expanded','false');
                    $('#logisticsInformation').removeClass('active').attr('aria-expanded','false');
                    $('#deliveryAddress').removeClass('active').attr('aria-expanded','false');
                    $('#customsInformation').addClass('active').attr('aria-expanded','true');

                }
                if(ac){
                    $('.deliveryAddress i').removeClass('fa-times text-danger');
                    $('.deliveryAddress i').addClass('fa-check text-success');
                }else{
                    $('.deliveryAddress i').removeClass('fa-check text-success');
                    $('.deliveryAddress i').addClass('fa-times text-danger');

                    $('.commentInformation a').removeClass('active');
                    $('.customsInformation a').removeClass('active');
                    $('.logisticsInformation a').removeClass('active');
                    $('.deliveryAddress a').addClass('active');

                    $('#commentInformation').removeClass('active').attr('aria-expanded','false');
                    $('#logisticsInformation').removeClass('active').attr('aria-expanded','false');
                    $('#customsInformation').removeClass('active').attr('aria-expanded','false');
                    $('#deliveryAddress').addClass('active').attr('aria-expanded','true');

                }

            }
        });


        $('#modal-OrderDetail .orderId').html('['+orderId+']');
        $('#modal-OrderDetail .orderAmount').html(orderAmount);
        $('#modal-OrderDetail .orderSeller').html(orderSeller);
        $('#modal-OrderDetail .orderBuyerId').html(buyerInfo.split('|')[1]);
        $('#modal-OrderDetail .orderBuyerName').html(buyerInfo.split('|')[0]);


        var contactNmae = $('#contactNmae');
        var address1 = $('#address1');
        var address2 = $('#address2');
        var phone = $('#phone');
        var mobile = $('#mobile');
        var country = $('#country');
        var city = $('#city');
        var province = $('#province');
        var zipCode = $('#zipCode');


        $.getJSON("/erp/api/getAddress?orderId="+orderId,function(data){
            if(data.error){
                console.log(data.msg);
                alert(data.msg);
                return false
            }else{

                if(data.address["address2"]!='None' && data.address["address2"]!=''){
                    address2.val(data.address["address2"]);
                }else{
                    address2.val('');
                }
                if(data.address["detailAddress"]!='None' && data.address["detailAddress"]!=''){
                    address1.val(data.address["detailAddress"]);
                }else{
                    address1.val('');
                }
                if(data.address["contactPerson"]!='None' && data.address["contactPerson"]!=''){
                    contactNmae.val(data.address["contactPerson"]);
                }else{
                    contactNmae.val('');
                }
                if(data.address["mobileNo"]!='None' && data.address["mobileNo"]!=''){
                    mobile.val(data.address["mobileNo"]);
                }else{
                    mobile.val('');
                }
                if(data.address["city"]!='None' && data.address["city"]!=''){
                    city.val(data.address["city"]);
                }else{
                    city.val('');
                }
                if(data.address["province"]!='None' && data.address["province"]!=''){
                    province.val(data.address["province"]);
                }else{
                    province.val('');
                }
                if(data.address["zip"]!='None' && data.address["zip"]!=''){
                    zipCode.val(data.address["zip"]);
                }else{
                    zipCode.val('');
                }


                if(data.address["phoneNumber"]!='None' && data.address["phoneNumber"]!='' ){
                    var phoneNo = ''
                    if(data.address["phoneCountry"]!='None' && data.address["phoneCountry"]!=''){
                        phoneNo += data.address["phoneCountry"];
                        phoneNo += '-';
                    }
                    if(data.address["phoneArea"]!='None' && data.address["phoneArea"]!=''){
                        phoneNo += data.address["phoneArea"];
                        phoneNo += '-';
                    }

                    phoneNo += data.address["phoneNumber"];

                    phone.val(phoneNo);

                }


                country.html('<option selected value="'+data.address["country"]+'">'+data.address["country_name"]+'('+data.address["country_name_cn"]+')</option>');
                $('#select2-country-container').html(data.address["country_name"]+'('+data.address["country_name_cn"]+')');

                country.val(data.address["country"]);

            }
        });

        var childOrder = $('#modal-OrderDetail .childOrder');
        var declareBox = $('#modal-OrderDetail .declareBox');
        childOrder.html('');
        declareBox.html('');

        $.getJSON("/erp/api/getChildOrder?orderId="+orderId,function(data){
            if(data.error){
                console.log(data.msg);
                alert(data.msg);
                return false
            }else{
                var html = '';
                var declare = '';
                $.each(data.childOrder, function (i, order) {
                    //html += '<tr data-val="'+order['orderId']+'|'+order['productId']+'"><td><a href="#">'+order['orderId']+'</a></td>';
                    html += '<tr data-val="'+order['orderId']+'|'+order['productId']+'"><td><a href="#">'+order['childOrderId']+'</a></td>';
                    declare += '<tr data-val="'+order['orderId']+'|'+order['productId']+'"><td><a href="javascript:;">'+order['productId']+'</a></td>';

                    if(order['productAttributes']['sku'].length>0){


                        var imgtxt = '';
                        var skutxt = '';

                        $.each(order['productAttributes']['sku'],function(i,sku){
                            var skuImg = sku['skuImg'];

                            if(skuImg.length>0 && imgtxt.length<=0){
                                imgtxt += skuImg;
                            }

                            var pName = sku['pName'];
                            var selfDefineValue = sku['selfDefineValue'];
                            var pValue = sku['pValue'];
                            if(selfDefineValue.length>0){
                                pValue = selfDefineValue;
                            }
                            skutxt += '<span class="m0">'+pName+':'+pValue+'</span><br>';

                        });

                        if(imgtxt.length<=0){
                            if(order['thumbnail'].length>0){
                                imgtxt += order['thumbnail']+'_50x50.jpg';
                            }else{
                                imgtxt += '/static/aside/images/nopic.png';
                            }

                        }else{
                            imgtxt = 'http://g02.a.alicdn.com/kf/'+imgtxt+'_50x50.jpg';
                        }

                        html += '<td><img src="'+imgtxt+'" class="w-48 img-responsive pull-left m-r" alt="">';
                        html += '<div class="clear"><span class="m0">'+order['productId']+'&nbsp;x&nbsp;<span class="label rounded danger">'+order['productCount']+'</span></span><br>';
                        html += '<span class="m0">'+order['currencyCode']+' '+order['unitPrice']+'</span><br>';
                        html += skutxt;

                        html += order['lotNum']+' '+order['productUnit'];
                        html +='</div></td>';

                    }else{
                        var imgtxt = '';
                        if(order['thumbnail'].length>0){
                            imgtxt += order['thumbnail']+'_50x50.jpg';
                        }else{
                            imgtxt += '/static/aside/images/nopic.png';
                        }
                        html += '<td><img src="'+imgtxt+'" class="w-48 img-responsive pull-left m-r" alt=""><div class="clear">';
                        html += '<span class="m0">'+order['productId']+'&nbsp;x&nbsp;<span class="label rounded danger">'+order['productCount']+'</span></span><br>';
                        html += '<span class="m0">'+order['currencyCode']+' '+order['unitPrice']+'</span><br>';

                        html += order['lotNum']+' '+order['productUnit'];
                        html += '</div></td>';
                    }

                    if('chinese_name' in order['declare']){
                        html += '<td>'+order['declare']['chinese_name']+' / '+order['declare']['english_name']+' / $ '+order['declare']['amount']+' / '+order['declare']['weight']+' (g) </td>';
                        declare += '<td data-val="'+order['declare']['chinese_name']+'|'+order['declare']['english_name']+'|'+order['declare']['amount']+'|'+order['declare']['weight']+'">'+order['declare']['chinese_name']+' / '+order['declare']['english_name']+' / $ '+order['declare']['amount']+' / '+order['declare']['weight']+' (g) </td>';
                    }else{
                        html += '<td><code>未填写</code></td>';
                        declare += '<td data-val="None"><code>请点击「编辑」，填写报关信息</code></td>';
                    }

                    html += '<td><button class="md-btn md-raised m-b-sm w-xs blue matchDeclare">配对</button></td></tr>';

                    declare += '<td><a href="javascript:;" class="editDeclare">编辑</a></td></tr>';

                });

                var buyerSelectChannel = data.childOrder[0]['logisticsType'];
                $('.logisticsName').html(buyerSelectChannel);

                childOrder.html(html);
                declareBox.html(declare);
            }
        });

        $.getJSON('/erp/api/checkOrderLogistics?orderId='+orderId,function(data){
            if(data.error){
                //console.log(data.msg);
                alert(data.msg);
                return false
            }else{
                var sendLogistics = data.sendLogistics;
                var deliveryLogistics = data.deliveryLogistics;
                var chooseLogistics = data.chooseLogistics;

                if(sendLogistics.count>0){
                    $('#noSelectChannel').html(sendLogistics.Logistics[0]['logisticsServiceName']);
                    var logisticsNo = '';
                    $.each(sendLogistics.Logistics,function(i,logis){
                        logisticsNo += logis['logisticsNo'] + '<br>';
                    });
                    $('#logisticsNoBox .logisticsNo').html(logisticsNo);
                    $('#logisticsNoBox').show();
                }else{
                    if(deliveryLogistics.count>0){
                        //console.log('已经在系统有发货记录');
                        $('#noSelectChannel').html(deliveryLogistics.Logistics[0]['channel']);
                        var logisticsNo = '';
                        $.each(deliveryLogistics.Logistics,function(i,logis){
                            logisticsNo += logis['logicstics_no'] + '<br>';
                        });
                        $('#logisticsNoBox .logisticsNo').html(logisticsNo);
                        $('#logisticsNoBox').show();
                    }else{
                        if(chooseLogistics.count>0){
                            //console.log('已经选择物流');
                            $('#logisticsNoBox').hide();
                            var html = '';
                            html += chooseLogistics.Logistics[0]['channel'];
                            html += '<a href="javascript:;" class="text-danger m-l-1"><i class="fa fa-pencil m-r-xs"></i>「更换」物流方式</a>';
                            $('#noSelectChannel').html(html);
                            $('.getNoMethod button').show();
                        }else{
                            //console.log('物流方式未选择');
                            $('#channelBox').hide();
                            $('#noSelectChannel').show();
                            var html = '<a href="javascript:;" class="text-danger"><i class="fa fa-pencil m-r-xs"></i>请点此「编辑」选择物流方式</a>';
                            $('#noSelectChannel').html(html);
                            $('#logisticsNoBox .logisticsNo').html('');
                            $('#logisticsNoBox').hide();
                            $('.getNoMethod').html('<span>手动上传</span><button class="m-l-2 form-control btn btn-sm info w-sm" type="button" style="display:none;">申请运单号</button>');
                        }
                    }
                }

            }
        });

        $('#modal-OrderDetail').modal('show');
        //console.log(orderSeller);
    });
    //编辑申报信息
    $(document).on('click','.editDeclare',function(){
        var info = $(this).parent().parent().attr('data-val');
        var orderId = info.split('|')[0];
        var productId = info.split('|')[1];
        var declareInfo = $(this).parent().parent().children('td').eq(1).attr('data-val');

        var chineseNmae = '';
        var englishNmae = '';
        var amount = '3.0';
        var weight = '100';

        if(declareInfo!='None'){
            var di = declareInfo.split('|');
            //console.log(di);
            chineseNmae = di[0]
            englishNmae = di[1]
            amount = di[2]
            weight = di[3]
        }

        $('#declareInformation table').hide();
        var html = '<form role="form" id="declareForm">';
        html += '<input type="hidden" name="declareOrderId" id="declareOrderId" value="'+orderId+'">';
        html += '<div class="col-xs-7">';
        html += '<div class="form-group row"><label for="declareProductId" class="col-sm-2 form-control-label p-r-0">产品ID:</label>';
        html += '<div class="col-sm-10"><input type="text" class="form-control has-value" id="declareProductId" value="'+productId+'" disabled></div></div>';
        html += '<div class="form-group row"><label for="chineseNmae" class="col-sm-2 form-control-label p-r-0">中文名称:</label>';
        html += '<div class="col-sm-10"><input type="text" class="form-control has-value" id="chineseNmae" value="'+chineseNmae+'"></div></div>';
        html += '<div class="form-group row"><label for="englishNmae" class="col-sm-2 form-control-label p-r-0">英文名称:</label>';
        html += '<div class="col-sm-10"><input type="text" class="form-control" id="englishNmae" value="'+englishNmae+'"></div></div>';
        html += '</div>';
        html += '<div class="col-xs-5">';
        html += '<div class="form-group row"><label for="declareAmount" class="col-sm-4 form-control-label p-r-0">申报金额:</label>';
        html += '<div class="col-sm-8"><div class="input-group"><span class="input-group-addon">$</span> <input type="text" id="declareAmount" class="form-control inputPrice" value="'+amount+'"> <span class="input-group-addon">USD</span></div></div></div>';
        html += '<div class="form-group row"><label for="declareWeight" class="col-sm-4 form-control-label p-r-0">申报重量:</label>';
        html += '<div class="col-sm-8"><div class="input-group"><span class="input-group-addon"></span> <input type="text" id="declareWeight" class="form-control inputNumber" value="'+weight+'"> <span class="input-group-addon">g</span></div></div></div>';
        html += '<div class="form-group row"><label for="declareCode" class="col-sm-4 form-control-label p-r-0">海关编码:</label>';
        html += '<div class="col-sm-8"><input type="text" class="form-control" name="declareCode" palceholder="非必填"></div></div>';
        html += '</div>';
        html += '<div class="row pull-right p-r-2 p-b-1">';
        html += '<label class="radio-inline p-r-1"><input type="radio" name="updateDeclare" value="0" checked class="has-value">仅修改当前订单</label>';
        html += '<label class="radio-inline p-r-1"><input type="radio" name="updateDeclare" value="1" class="has-value">修改相同SKU的所有「待审核」「待处理」订单</label>';
        html += '<button type="button" class="btn btn-xs primary rounded m-l-2 p-r-1 cannel" name="cannel"><i class="fa fa-pencil m-r-xs"></i> 放弃</button>';
        html += '<button type="button" class="btn btn-xs info rounded save" name="save"><i class="fa fa-save m-r-xs"></i> 保存</button></div>';
        html +='</form>';

        $('#declareInformation').append(html);

    });
    $(document).on('click', '#declareForm .cannel', function() {
        $('#declareInformation #declareForm').remove();
        $('#declareInformation table').show();
    });
    $(document).on('click', '#declareForm .save', function() {
        var orderId = $("#declareForm #declareOrderId").val()
        var productId = $("#declareForm #declareProductId").val()
        var chineseNmae = $("#declareForm #chineseNmae").val()
        var englishNmae = $("#declareForm #englishNmae").val()
        var amount = $("#declareForm #declareAmount").val()
        var weight = $("#declareForm #declareWeight").val()
        var code = $("#declareForm #declareCode").val()
        var updateType = $("#declareForm input[name='updateDeclare']:checked").val();
        if((chineseNmae.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0){
            alert('申报中文名称不能为空');
            $("#declareForm #chineseNmae").focus();
            return false
        }
        if((englishNmae.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0){
            alert('申报英文名称不能为空');
            $("#declareForm #englishNmae").focus();
            return false
        }
        if((amount.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0 || parseFloat(amount)<=0){
            alert('申报金额须大于0');
            $("#declareForm #declareAmount").focus();
            return false
        }
        if((weight.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"")).length==0 || parseInt(weight)<=0){
            alert('申报重量须大于0');
            $("#declareForm #declareWeight").focus();
            return false
        }

        var dd = { orderId: orderId, productId: productId,cName:chineseNmae,eName:englishNmae,amount:amount,weight:weight,code:code,type:updateType }


        var childOrder = $('#modal-OrderDetail .childOrder');
        var declareBox = $('#modal-OrderDetail .declareBox');
        childOrder.html('');
        declareBox.html('');

        $.getJSON('/erp/api/editProductDeclare',dd,function(data){
            if(data.error){
                console.log('保存失败');
            }else{
                //console.log('保存成功');


                $('#modal-OrderDetail').block({
                    message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
                    css: { border: "none",backgroundColor: "transparent",color: "#fff",padding: "30px",width: "100%"},
                    timeout: 3e3
                });


                $.getJSON('/erp/api/getChildOrder?orderId='+orderId,function(orderData){

                    var html = '';
                    var declare = '';
                    $.each(orderData.childOrder, function (i, order) {
                        html += '<tr data-val="'+order['orderId']+'|'+order['productId']+'"><td><a href="#">'+order['orderId']+'</a></td>';
                        declare += '<tr data-val="'+order['orderId']+'|'+order['productId']+'"><td><a href="javascript:;">'+order['productId']+'</a></td>';

                        if(order['productAttributes']['sku'].length>0){


                            var imgtxt = '';
                            var skutxt = '';

                            $.each(order['productAttributes']['sku'],function(i,sku){
                                var skuImg = sku['skuImg'];

                                if(skuImg.length>0 && imgtxt.length<=0){
                                    imgtxt += skuImg;
                                }

                                var pName = sku['pName'];
                                var selfDefineValue = sku['selfDefineValue'];
                                var pValue = sku['pValue'];
                                if(selfDefineValue.length>0){
                                    pValue = selfDefineValue;
                                }
                                 skutxt += '<span class="m0">'+pName+':'+pValue+'</span><br>';

                            });

                            if(imgtxt.length<=0){
                                if(order['thumbnail'].length>0){
                                    imgtxt += order['thumbnail']+'_50x50.jpg';
                                }else{
                                    imgtxt += '/static/aside/images/nopic.png';
                                }

                            }else{
                                imgtxt = 'http://g02.a.alicdn.com/kf/'+imgtxt+'_50x50.jpg';
                            }

                            html += '<td><img src="'+imgtxt+'" class="w-48 img-responsive pull-left m-r" alt="">';
                            html += '<div class="clear"><span class="m0">'+order['productId']+'&nbsp;x&nbsp;<span class="label rounded danger">'+order['productCount']+'</span></span><br>';
                            html += '<span class="m0">'+order['currencyCode']+' '+order['unitPrice']+'</span><br>';
                            html += skutxt;
                            html +='</div></td>';

                        }else{
                            var imgtxt = '';
                            if(order['thumbnail'].length>0){
                                imgtxt += order['thumbnail']+'_50x50.jpg';
                            }else{
                                imgtxt += '/static/aside/images/nopic.png';
                            }
                            html += '<td><img src="'+imgtxt+'" class="w-48 img-responsive pull-left m-r" alt=""><div class="clear">';
                            html += '<span class="m0">'+order['productId']+'&nbsp;x&nbsp;<span class="label rounded danger">'+order['productCount']+'</span></span><br>';
                            html += '<span class="m0">'+order['currencyCode']+' '+order['unitPrice']+'</span><br>';
                            html += '</div></td>';
                        }

                        if('chinese_name' in order['declare']){
                            html += '<td>'+order['declare']['chinese_name']+' / '+order['declare']['english_name']+' / $ '+order['declare']['amount']+' / '+order['declare']['weight']+' (g) </td>';
                            declare += '<td data-val="'+order['declare']['chinese_name']+'|'+order['declare']['english_name']+'|'+order['declare']['amount']+'|'+order['declare']['weight']+'">'+order['declare']['chinese_name']+' / '+order['declare']['english_name']+' / $ '+order['declare']['amount']+' / '+order['declare']['weight']+' (g) </td>';
                        }else{
                            html += '<td><code>未填写</code></td>';
                            declare += '<td data-val="None"><code>请点击「编辑」，填写报关信息</code></td>';
                        }

                        html += '<td><button class="md-btn md-raised m-b-sm w-xs blue matchDeclare">配对</button></td></tr>';

                        declare += '<td><a href="javascript:;" class="editDeclare">编辑</a></td></tr>';

                    });


                childOrder.html(html);
                declareBox.html(declare);

                });
            }
        });

        $('.customsInformation i').removeClass('fa-times text-danger');
        $('.customsInformation i').addClass('fa-check text-success');

        $('#declareInformation #declareForm').remove();
        $('#declareInformation table').show();
    });
    //展开订单详情面板
    $(document).on('click', '.orderItem', function() {
        var orderId = $(this).text();
        $('#selectedLine').val($(this).parent().parent().index());
        //console.log(orderId);

        var childOrder = $('#goodsInfoBox .childOrder');
        childOrder.html('');

        $.getJSON("/erp/api/getChildOrder?orderId="+orderId,function(data){
            if(data.error){
                console.log(data.msg);
                alert(data.msg);
                return false
            }else{
                var html = ''
                $.each(data.childOrder, function (i, order) {
                    var idx = parseInt(i)+1;
                    html += '<tr><td><a href="#">'+idx+'</a></td>'
                    if(order['productAttributes']['sku'].length>0){

                        var imgtxt = '';
                        var skutxt = '';

                        $.each(order['productAttributes']['sku'],function(i,sku){
                            var skuImg = sku['skuImg'];

                            if(skuImg.length>0 && imgtxt.length<=0){
                                imgtxt += skuImg;
                            }

                            var pName = sku['pName'];
                            var selfDefineValue = sku['selfDefineValue'];
                            var pValue = sku['pValue'];
                            if(selfDefineValue.length>0){
                                pValue = selfDefineValue;
                            }
                             skutxt += '<span class="m0">'+pName+':'+pValue+'</span><br>';

                        });

                        if(imgtxt.length<=0){
                            if(order['thumbnail'].length>0){
                                imgtxt += order['thumbnail']+'_50x50.jpg';
                            }else{
                                imgtxt += '/static/aside/images/nopic.png';
                            }

                        }else{
                            imgtxt = 'http://g02.a.alicdn.com/kf/'+imgtxt+'_50x50.jpg';
                        }

                        html += '<td><img src="'+imgtxt+'" class="w-48 img-responsive pull-left m-r" alt="">';
                        html += '<div class="clear"><span class="m0">'+order['productId']+'&nbsp;x&nbsp;<span class="label rounded danger">'+order['productCount']+'</span></span><br>';
                        html += '<span class="m0">'+order['currencyCode']+' '+order['unitPrice']+'</span><br>';
                        html += skutxt;
                        html += order['lotNum']+' '+order['productUnit'];
                        html +='</div></td>';

                    }else{
                        var imgtxt = '';
                        if(order['thumbnail'].length>0){
                            imgtxt += order['thumbnail']+'_50x50.jpg';
                        }else{
                            imgtxt += '/static/aside/images/nopic.png';
                        }
                        //html += '<td><img src="'+imgtxt+'" class="w-48 img-responsive pull-left m-r" alt=""></td>';
                        html += '<td><img src="'+imgtxt+'" class="w-48 img-responsive pull-left m-r" alt=""><div class="clear">';
                        html += '<span class="m0">'+order['productId']+'&nbsp;x&nbsp;<span class="label rounded danger">'+order['productCount']+'</span></span><br>';
                        html += '<span class="m0">'+order['currencyCode']+' '+order['unitPrice']+'</span><br>';

                        html += order['lotNum']+' '+order['productUnit'];
                        html += '</div></td>';
                    }

                    if('chinese_name' in order['declare']){
                        html += '<td>'+order['declare']['chinese_name']+' / '+order['declare']['english_name']+' / $ '+order['declare']['amount']+' / '+order['declare']['weight']+' (g) </td>';
                    }else{
                        html += '<td><code>未填写</code></td>';
                    }
                    html += '<td>'+order['currencyCode']+' '+order['unitPrice']+'</td>';
                    html += '<td>'+order['productCount']+'</td>';
                    html += '<td>'+order['totalAmount']+'</td>';
                    html += '<td> - </td>';

                });

                childOrder.html(html);


            }
        });


        var contactInfo = $('#goodsInfoBox .contactInfo');
        contactInfo.html('');

        $.getJSON("/erp/api/getAddress?orderId="+orderId,function(data){
            if(data.error){
                console.log(data.msg);
                alert(data.msg);
                return false
            }else{

                var html = ''

                html +='<tr><td>';

                if(data.address["contactPerson"]!='None' && data.address["contactPerson"]!=''){
                    html += data.address["contactPerson"]+'';
                }
                html += '</td><td>';
                if(data.address["country"]!='None' && data.address["country"]!=''){
                    html += data.address["country_name"]+' ( '+data.address["country_name_cn"]+' ) / '+data.address["country"];
                }

                html += '</td><td>';
                if(data.address["province"]!='None' && data.address["province"]!=''){
                    html += data.address["province"];
                }
                html += '</td><td>';

                if(data.address["city"]!='None' && data.address["city"]!=''){
                    html += data.address["city"];
                }
                html += '</td><td>';

                if(data.address["detailAddress"]!='None' && data.address["detailAddress"]!=''){
                    html += data.address["detailAddress"];
                }
                if(data.address["address2"]!='None' && data.address["address2"]!=''){
                    html += ' / '+data.address["address2"];
                }
                html += '</td><td>';

                if(data.address["zip"]!='None' && data.address["zip"]!=''){
                    html += data.address["zip"];
                }
                html += '</td><td>';

                var phoneNo = ''
                if(data.address["phoneNumber"]!='None' && data.address["phoneNumber"]!='' ){
                    if(data.address["phoneCountry"]!='None' && data.address["phoneCountry"]!=''){
                        phoneNo += data.address["phoneCountry"];
                        phoneNo += '-';
                    }
                    if(data.address["phoneArea"]!='None' && data.address["phoneArea"]!=''){
                        phoneNo += data.address["phoneArea"];
                        phoneNo += '-';
                    }

                    phoneNo += data.address["phoneNumber"];

                }
                if(phoneNo.length>0){
                    html += '电话：'+phoneNo+'<br>';
                }
                if(data.address["mobileNo"]!='None' && data.address["mobileNo"]!=''){
                    html +='手机：'+data.address["mobileNo"];
                }

                html += '</td></tr>';


                contactInfo.html(html);

            }
        });

        var memoInfo = $('#goodsInfoBox .memoInfo');
        memoInfo.html('');
        $.getJSON('/erp/api/getOrderMemo?orderId='+orderId,function(data){
            if(data.error){
                console.log(data.msg);
                alert(data.msg);
                return false
            }else{
                var html = '';
                if(data.result.length>0){
                    $.each(data.result,function(i,memo){
                        html += '<tr><td>';
                        html += memo['content'];
                        html += '</td><td>';
                        if(memo['type']=='1'){
                            html += '拣货说明';
                        }else{
                            html += '客服备注';
                        }
                        html += '</td><td>';
                        html += memo['time'];
                        html += '</td></tr>';
                    });

                }

                memoInfo.html(html);

            }
        });

        var msg = $(this).parent().children('a.showMsg');
        if(msg.length>0){
            var msgEN = msg.attr('title');
            var msgCN = msg.attr('data-translate');
            var html = '<p><code>原文：</code> '+msgEN+'</p>';
            html += '<p><code>翻译：</code> '+msgCN+'</p>';
            $('#tab-message').html(html);
        }else{
            $('#tab-message').html('无');
        }

        $('#goodsInfoBox').show();
    });

    $(document).on('click','.translateDeclareEN',function(){
        var words = $('#dNameCN').val();
        if(words.length>0){
            $.getJSON('/erp/api/Translate?words='+words+'&to=en',function(data){
                if(data.success){
                    var trans = $('#dNameEN');
                    trans.val(data.result);
                }
            });
        }
    });
    $(document).on('click','.translateDeclareZH',function(){
        var words = $('#dNameEN').val();
        if(words.length>0){
            $.getJSON('/erp/api/Translate?words='+words+'&to=zh',function(data){
                if(data.success){
                    var trans = $('#dNameCN');
                    trans.val(data.result);
                }
            });
        }
    });

    //显示留言
    $(document).on('click', '.showMsg', function() {
        var msg = $(this).attr('title');
        var msgTranslate = $(this).attr('data-translate');
        var orderId = $(this).parent().parent().attr('data-val');
        $('#selectedOrder').val(orderId);
        //console.log(orderId);

        var msgBox = $('#chat .messageList');
        msgBox.html('');

        var html = '';
        html += '<div class="m-b"><a href="#" class="pull-left w-40 m-r-sm"><img src="/static/aside/images/a2.jpg" alt="..." class="w-full img-circle"></a>';
        html += '<div class="clear">';
        html += '<div class="p-a p-y-sm dark-white inline r msgContent">';
        html += msg;
        html += '</div>';
        if(msgTranslate.length>0){
            html += '<div class="p-a p-y-sm success inline r msgTranslte m-t-1">'+msgTranslate+'</div>';
            $('.oneKeyTranslate').attr('disabled','disabled');
        }else{
            html += '<div class="p-a p-y-sm success inline r msgTranslte m-t-1" style="display:none;"></div>';
            $('.oneKeyTranslate').removeAttr('disabled');
        }
        html += '<div class="text-muted text-xs m-t-xs"><i class="fa fa-ok text-success"></i>2 minutes ago</div></div></div>';

        msgBox.html(html);

        $('#chat').modal('show');

    });
    //翻译
    $(document).on('click', '.oneKeyTranslate', function() {
        var words = $('.msgContent').text();
        //console.log(words);
        //console.log(escape(words));
        $("#chat .row-inner").block({
            message: '<i class="fa fa-lg fa-refresh fa-spin"></i>',
            css: { border: "none",backgroundColor: "transparent",color: "#fff",padding: "30px",width: "100%"},
            timeout: 3e3
        });
        $.getJSON('/erp/api/Translate?words='+escape(words),function(data){
            if(data.success){
                var trans = $('.msgTranslte');
                trans.html(data.result);
                trans.css('display','block');
            }
        });


    });

    //备注订单
    $(document).on('click', '.orderMemo', function() {
        var orderId = $(this).parent().parent().attr('data-val');
        $('#selectedOrder').val(orderId);
        $('#modal-memo .orderId').html('['+orderId+']');
        $('#memoOrderID').val(orderId);
        $('#selectedLine').val($(this).parent().parent().index());

    });
    $(document).on('click', '.addMemo', function() {
        var orderId = $('#selectedOrder').val();
        $('#modal-memo .orderId').html('['+orderId+']');
        $('#memoOrderID').val(orderId);
    });
    //提交备注
    $(document).on('click', '#submitMemo', function() {
        var memoForm = $('#memoForm');

        memoForm.ajaxSubmit({
            success: function(data) {
                if(data.error){
                    alert(data.msg);
                    return false;
                }else{
                    //$('#modal-memo').modal('hide');
                    $('#modal-memo #memoContent').val('');
                    var memoType = $('#memoForm #memoType').val();
                    var html = '';
                    if(memoType == '1'){
                        html += ' <a href="javascript:;" class="label success text-white showMemo orderMemo" data-type="1">拣</a> ';
                    }else{
                        html += ' <a href="javascript:;" class="label warn text-white showMemo orderMemo" data-type="2">备</a> ';
                    }
                    var selectedLine = parseInt($('#selectedLine').val());
                    var obj = $('#OrderListBox').children('tr').eq(selectedLine).children('td').eq(1).children('.separator');
                    obj.before(html)
                    //loadOrderList();
                }
            }
        });

        $('#modal-memo').modal('hide');
    });

    //打印面单
    $(document).on('click', '.printMb', function() {
        $('#selectedLine').val($(this).parent().parent().index());
        var orderId = $(this).parent().parent().attr('data-val');
        //console.log(orderId);
        window.open('/static/aside/printMb.pdf');
        $('#modal-printMB').modal('show');
    });

    //产品开发页面
    $(document).on('click', '#uploadBtn', function() {
        var imgFile = $('input[name="imgFile"]');
        var remoteImgURL = $('input[name="remoteImgURL"]');
        var list = $('#skuImgList');
        var box = $('#skuListBox');
        var imgPlace = $('#imgPlace').val();
        //var count = list.children().length;
        var count = box.children().length;
        if(imgFile.val().length>0){
            var skuCode = $('#skuCode').val();
            $('#uploadImgForm').ajaxSubmit({
                success: function(data) {
                    //console.log(data);
                    if(data.error){
                        alert(data.message);
                    }else{
                        count += 1;
                        //console.log(count);

                        if(count < 2){
                            var html = '<div class="col-md-12"><div class="box p-a-xs"><img src="'+data.url+'" alt="" class="img-responsive"></div></div>';
                            list.html(html);
                        }

                        if(imgPlace == 'None'){
                            //var html = '<div class="col-xs-3 col-sm-2 col-md-1"><div class="box p-a-xs"><img src="'+data.url+'" alt="" class="img-responsive"></div></div>';
                            var txt = '<tr class="skuItem" data-val="'+count+'">';
                            txt += '<td><img src="'+data.url+'" class="w-48 img-responsive skuImg" data-index="'+count+'" /></td>';
                            txt += '<td><input type="text" disabled value="'+skuCode+':'+count+'" class="form-control subSukCode" data-index="'+count+'" /></td>';
                            txt += '<td><input type="text" value="" class="form-control" /></td>';
                            txt += '<td><input type="text" value="" class="form-control inputPrice w-xs sellPrice" /></td>';
                            txt += '<td><input type="text" value="" class="form-control inputPrice w-xs purchasePrice" /></td>';
                            txt += '<td><input type="text" value="" class="form-control w-xs" disabled /></td>';
                            txt += '</tr>';

                            $('#skuListBox').append(txt);

                            list.append(html);
                        }else{

                            var idx = parseInt(imgPlace)-1;
                            box.children().eq(idx).children().eq(0).children().eq(0).attr('src',data.url);
                            if(parseInt(imgPlace)==1){
                                list.html('<div class="col-md-12"><div class="box p-a-xs"><img src="'+data.url+'" alt="" class="img-responsive"></div></div>');
                            }

                        }

                        imgFile.val('');
                        remoteImgURL.val('');

                    }
                }
            });

        }

        if(remoteImgURL.val().length>0){
            var url = remoteImgURL.val();
            var skuCode = $('#skuCode').val();
            count += 1;

            if(count < 2){
                var html = '<div class="col-md-12"><div class="box p-a-xs"><img src="'+url+'" alt="" class="img-responsive"></div></div>';
                list.html(html);
            }

            imgFile.val('');
            remoteImgURL.val('');

            if(imgPlace == 'None'){
                var txt = '<tr class="skuItem" data-val="'+count+'">';
                txt += '<td><img src="'+url+'" class="w-48 img-responsive skuImg" data-index="'+count+'" /></td>';
                txt += '<td><input type="text" disabled value="'+skuCode+':'+count+'" class="form-control subSukCode" data-index="'+count+'" /></td>';
                txt += '<td><input type="text" value="" class="form-control" /></td>';
                txt += '<td><input type="text" value="" class="form-control inputPrice w-xs sellPrice" /></td>';
                txt += '<td><input type="text" value="" class="form-control inputPrice w-xs purchasePrice" /></td>';
                txt += '<td><input type="text" value="" class="form-control w-xs" disabled /></td>';
                txt += '</tr>';

                $('#skuListBox').append(txt);

            }else{
                //console.log(parseInt(imgPlace)-1);
                var idx = parseInt(imgPlace)-1;
                box.children().eq(idx).children().eq(0).children().eq(0).attr('src',url);
                if(parseInt(imgPlace)==1){
                    list.html('<div class="col-md-12"><div class="box p-a-xs"><img src="'+url+'" alt="" class="img-responsive"></div></div>');
                }
            }



        }

        $('#modal-uploadImage').modal('hide');

    });

    $(document).on('change', '.skuItem .sellPrice', function() {
        var exchangeRate = parseFloat($('#exchangeRate').val());
        var sellPrice = $(this).val();
        var purchasePrice = $(this).parent().parent().children().eq(4).children().eq(0).val();
        var gross = 0;
        if(sellPrice.length >0 && purchasePrice.length>0){
            gross = parseFloat(sellPrice)*exchangeRate - parseFloat(purchasePrice);
        }

        $(this).parent().parent().children().eq(5).children().eq(0).val(gross.toFixed(2));

    });

    $(document).on('change', '.skuItem .purchasePrice', function() {
        var exchangeRate = parseFloat($('#exchangeRate').val());
        var purchasePrice = $(this).val();
        var sellPrice = $(this).parent().parent().children().eq(3).children().eq(0).val();
        var gross = 0;
        if(sellPrice.length >0 && purchasePrice.length>0){
            gross = parseFloat(sellPrice)*exchangeRate - parseFloat(purchasePrice);
        }

        $(this).parent().parent().children().eq(5).children().eq(0).val(gross.toFixed(2));

    });

    //生成SKU编码：getSkuCode
    $(document).on('click', '.getSkuCode', function() {
        var type = $('#dCategory').val();
        $.getJSON("/erp/api/getSkuCode",function(data){
            var skuCode = type+'-'+data.skuCode;
            $('#skuCode').val(skuCode);
            var obj = $('.subSukCode');
            //console.log(obj);
            for(var i=0; i<obj.length; i++){
                var idx = obj[i].getAttribute('data-index');
                obj[i].value = skuCode+':'+idx;
            }
        });

    });
    $(document).on('change', '#dCategory', function() {
        var type = $(this).val();
        $.getJSON("/erp/api/getSkuCode",function(data){
            var skuCode = type+'-'+data.skuCode;
            $('#skuCode').val(skuCode);
            var obj = $('.subSukCode');
            //console.log(obj);
            for(var i=0; i<obj.length; i++){
                var idx = obj[i].getAttribute('data-index');
                obj[i].value = skuCode+':'+idx;
            }
        });
    });
    //更换SKU图片
    $(document).on('click', '#skuListBox .skuImg', function() {
        $('#imgPlace').val($(this).attr('data-index'));
        $('#modal-uploadImage').modal('show');
    });
    //上传图片
    $(document).on('click', '.uplaodImage', function() {
        $('#imgPlace').val('None');
        $('#modal-uploadImage').modal('show');
    });

    $(document).on('click', '#getImgAndSKU', function() {
        var url = $('#smtUrl').val();
        var box = $('#skuListBox');

        var list = $('#skuImgList');
        var skuCode = $('#skuCode').val();

        if(url.length<=0){
             alert('请填写速卖通商品的URL');
             $('#smtUrl').focus();
             return false;
         }else{
            $.getJSON("/api/getSku/",
                     { url: url },
                     function(result){
                         //console.log(result);
              if("thumb" in result && result['thumb'].length > 0){
                  box.html('');
                  var count = box.children().length;


                  $.each(result["skuImg"], function (i, sku) {
                        count +=1;
                        var txt = '<tr class="skuItem" data-val="'+count+'">';
                        txt += '<td><img src="'+sku["img"]+'" alt="'+sku["name"]+'" class="w-48 img-responsive skuImg" data-index="'+count+'" /></td>';
                        txt += '<td><input type="text" disabled value="'+skuCode+':'+count+'" class="form-control subSukCode" data-index="'+count+'" /></td>';
                        txt += '<td><input type="text" value="'+sku["name"]+'" class="form-control" /></td>';
                        txt += '<td><input type="text" value="" class="form-control inputPrice w-xs sellPrice" /></td>';
                        txt += '<td><input type="text" value="" class="form-control inputPrice w-xs purchasePrice" /></td>';
                        txt += '<td><input type="text" value="" class="form-control w-xs" disabled /></td>';
                        txt += '</tr>';

                        box.append(txt);

                        if(count < 2){
                            var html = '<div class="col-md-12"><div class="box p-a-xs"><img src="'+sku["img"]+'" alt="'+sku["name"]+'" class="img-responsive"></div></div>';
                            list.html(html);
                        }

                  //box.append('<li><p><img src="'+sku["img"]+'" width=80 /></p><span>' + sku["name"] + '</span></li>');


                  }
                );


              }else{
                  alert('获取失败！');
              }
          });
        }
    });

    $(document).on('click','#copySellPrice',function(){
        var exchangeRate = parseFloat($('#exchangeRate').val());
        var box = $('#skuListBox');
        var count = box.children().length;
        if(count>0){
            var sellPrice = box.children().eq(0).children().eq(3).children().eq(0).val();
            if(sellPrice.length>0){
                $("input.sellPrice").each(function(i,item){
                    item.value = sellPrice;
                    var purchasePrice = box.children().eq(i).children().eq(4).children().eq(0).val();
                    var gross = 0;
                    if(purchasePrice.length>0){
                        gross = parseFloat(sellPrice)*exchangeRate - parseFloat(purchasePrice);
                    }

                    box.children().eq(i).children().eq(5).children().eq(0).val(gross.toFixed(2));
                });
            }
        }

    });

    $(document).on('click','#copyPurchasePrice',function(){
        var exchangeRate = parseFloat($('#exchangeRate').val());
        var box = $('#skuListBox');
        var count = box.children().length;
        if(count>0){
            var purchasePrice = box.children().eq(0).children().eq(4).children().eq(0).val();
            if(purchasePrice.length>0){
                $("input.purchasePrice").each(function(i,item){
                    item.value = purchasePrice;
                    var sellPrice = box.children().eq(i).children().eq(3).children().eq(0).val();
                    var gross = 0;
                    if(sellPrice.length>0){
                        gross = parseFloat(sellPrice)*exchangeRate - parseFloat(purchasePrice);
                    }

                    box.children().eq(i).children().eq(5).children().eq(0).val(gross.toFixed(2));
                });
            }
        }

    });

    $(document).on('keyup', '#setExchangeRate', function() {
        $('#exchangeRate').val($(this).val())
    });

    //图片预览
    $(document).on('mouseover','a.preview',function(e){

        $(this).parent().children().eq($(this).parent().children().length-1).append("<div id='preview' class='previewShowWindow'><img id='pi' src='/static/images/loading_sm.gif' alt='Now Loading' /></div>");
		var m=$(this).attr("data-src");
		$("#pi").attr("src",m);

        var t = 0;
        var l = 0;
        if($("#aside").hasClass('folded')){
            t = e.pageY-80;
            l = e.pageX-80;
        }else{
            t = e.pageY-100;
            l = e.pageX-200;
        }
        $("#preview").css("max-width", '300px').css("max-height", '300px').css("overflow", 'hidden').css("top", t).css("left", l).css("position",'absolute').fadeIn("slow");
	});
    $(document).on('mouseout', 'a.preview', function() {
        $("#preview").remove();
    });
    $(document).on('click', 'a.preview', function() {
        var id = $(this).attr('data-productid');
        console.log(id);
        window.open('http://www.aliexpress.com/item/-/'+id+'.html');
    });
    //显示备注
    $(document).on('mouseover','a.showMemo',function(e){
        var t = 0;
        var l = 0;
        if($("#aside").hasClass('folded')){
            t = e.pageY-200;
            l = e.pageX-80;
        }else{
            t = e.pageY-200;
            l = e.pageX-200;
        }
        $(this).parent().children().eq($(this).parent().children().length-1).append("<div id='memoBox' class='previewShowWindow'></div>");
        var memoBox = $("#memoBox");

        var type = $(this).attr('data-val');
        var orderId = $(this).parent().parent().attr('data-val');

        $.getJSON("/erp/api/getOrderMemo?orderId="+orderId+'&type='+type,function(data){
            if(data.error){
                //console.log(data.msg);
                memoBox.html(data.msg);
            }else{
                var result = data.result
                var count = result.length;
                var html = '';
                html += '<div class="box"><div class="box-header"><span class="label success pull-right">';
                html += count;
                html += '</span><h3>备注信息</h3></div><div class="box-body"><div class="streamline m-b">';
                if(count>0){
                    $.each(result,function (i, memo) {
                        html += '<div class="sl-item"><div class="sl-content">';
                        html += '<span class="m-l-sm sl-date">'+memo['time']+'</span>';
                        html += '<div>'+memo['content']+'</div>';
                        html += '</div></div>';
                    });
                }else{
                    html += '<p>无</p>';
                }
                html += '</div></div></div>';
                memoBox.html(html);
            }

        });

        memoBox.css("max-width", '500px').css("min-width", '300px').css("max-height", '300px').css("overflow", 'scroll').css("top", t).css("left", l).css("position",'absolute').fadeIn("slow");
    });
    $(document).on('mouseout', 'a.showMemo', function() {
        $("#memoBox").remove();
    });
    //编辑物流方式
    $(document).on('click', '#noSelectChannel a', function() {
        $('#noSelectChannel').hide();
        $('#channelBox').show();
    });
    //取消编辑
    $(document).on('click', '#channelBox .saveChannel', function() {
        //var channel = $('#selectLogisticsChanel').find("option:selected").val();
        var channelId = $('#selectLogisticsChanel').find("option:selected").val();
        var channelTxt = $('#selectLogisticsChanel').find("option:selected").text();

        var orderId = $('#selectedOrder').val();

        var selectedLine = parseInt($('#selectedLine').val());

        if(channelId=='0'){
            alert('请选择物流渠道');
            $('#selectLogisticsChanel').focus();
            return false
        }else{
            var channelCode = $('#selectLogisticsChanel').find("option:selected").attr('data-val');
            var channelType = $('#selectLogisticsChanel').find("option:selected").attr('data-type');
            $('#channelBox').hide();

            var data = {orderId:orderId,channelId:channelId,channelName:channelTxt,channelCode:channelCode,channelType:channelType}

            //console.log(data);
            $.post("/erp/api/selectLogistics/",data,function(result){
                //console.log(result);
                if(result.error){
                    console.log(result.msg);
                }else{
                    $('.logisticsInformation i').removeClass('fa-times text-danger');
                    $('.logisticsInformation i').addClass('fa-check text-success');
                    $('#OrderListBox').children('tr').eq(selectedLine).children('td').eq(6).html($('#selectLogisticsChanel').find("option:selected").text());
                }
            });

            channelTxt += ' <a href="javascript:;" class="text-danger m-l-1"><i class="fa fa-pencil m-r-xs"></i>「更换」物流方式</a>';
            $('#noSelectChannel').html(channelTxt);

            //$('.getNoMethod button').show();

            $('#noSelectChannel').show();
        }

        $('.getNoMethod').html('<span>自动获取</span><button class="m-l-2 form-control btn btn-sm info w-sm applyLogisticsNo" type="button" style="">申请运单号</button>');

    });
    //取消编辑
    $(document).on('click', '#channelBox .cannel', function() {

        $('#channelBox').hide();
        $('#noSelectChannel').show();
        var html = '<span>手动上传</span>';
        html += '<button class="m-l-2 form-control btn btn-sm info w-sm applyLogisticsNo" type="button" style="display:none;">申请运单号</button>';
        $('.getNoMethod').html(html);

        $('#selectLogisticsChanel').children().eq(0).attr("selected","selected");
        $("#selectLogisticsChanel").select2();
    });
    //选中物流，更新获取单号方式
    $(document).on('change', '#selectLogisticsChanel', function() {
        var html = '<span>自动获取</span>';
        html += '<button class="m-l-2 form-control btn btn-sm info w-sm applyLogisticsNo" type="button" style="display:none;">申请运单号</button>';
        $('.getNoMethod').html(html);
    });
    //更换运单号
    $(document).on('click', 'a.changeLogisticsNo', function() {
        alert('暂不支持');
    });
    //申请单号
    $(document).on('click', '.applyLogisticsNo', function() {
        var orderId = $('#selectedOrder').val();
        if(orderId!='None'){
            $.getJSON('/erp/api/applyLogisticsNo/?orderId='+orderId,function(data){

            });
        }

    });

    //拆分包裹
    $(document).on('click', '.btnSplitPackage', function() {
        //$('#modal-OrderDetail').modal('hide');
        $('#modal-SplitPackage').modal('show');
    });


    //物流渠道设置
    $(document).on('click', '.channelEnble', function() {
        var code = $(this).attr('data-val');
        var type = $(this).attr('data-type');
        var checked = '0'
        if($(this).is(':checked')){
            //alert(code+'选中');
            checked = '1';

        }
        var data = {code:code,checked:checked,type:type}
        $.getJSON('/erp/api/enbleChannel/',data,function(result){
            //console.log(result);
            if(result.error){
                alert('修改失败');
            }
        });
    });

    //同步订单
    $(document).on('click', '.synchronousOrderBtn', function() {

        var total = parseInt($('#totalTask').val());

        if(total>0){
            $('#synchronousOrderBar').show();
            setInterval(startRequest,300);
        }else{
            alert('没有需要同步的订单了哦！');
            $('#synchronousOrderBar').fadeOut(3000);
            clearInterval();
        }
    });

    //速卖通线上渠道管理
    $(document).on('click', '.editChannel', function() {
        $('#modal-editChannel .modal-title span').html(' [ '+$(this).attr('data-serviceName')+' ]');
        $('#modal-editChannel').modal('show');
        var q = $(this).attr('data-val');
        var container = $('#modal-editChannel tbody');
        //var container = $('#modal-editChannel .modal-body');
        //container.load('/erp/api/getSmtLogisticsChanel/?q='+q, function( response, status, xhr ) {
        //  container.html(response);
        //});
        $.getJSON('/erp/api/getSmtLogisticsChanel/?q='+q,function(data){
            var html = '';
            if(data.total_count>0){
                container.html('');

                $.each(data.result,function(idx,channel){
                    html += '<tr data-val="'+channel['logisticsServiceId']+'">';
                    html += '<td>'+channel['warehouseName']+'</td>';
                    html += '<td>'+channel['logisticsTimeliness']+'</td>';
                    html += '<td data-value="'+channel['enabled']+'"><label class="ui-switch danger m-t-xs m-r">';
                    html += '<input type="checkbox" ';
                    if(channel['enabled']=='1'){
                        html += 'checked="checked"';
                    }
                    html += 'class="has-value channelEnble" data-val="'+channel['logisticsServiceId']+'" data-type="child"> <i></i></label></td>';
                    html += '<td>设置 ｜ <a href="javascript:;" class="text-info editChannelInfo">编辑自定义名称</a></td>';
                    html += '</tr>';
                });

                container.html(html);
                $('#modal-editChannel table').footable();
                //$('.footable').footable()
            }else{
                container.html('');
                console.log('无数据');
            }
        });
    });
    //编辑物流服务商信息
    $(document).on('click', '.editChannelInfo', function() {
        var channel = $(this).parent().parent().attr('data-val');
        $('#editLogisticsServiceId').val(channel);
        $('#modal-editChannelInfo').modal('show');
    });
    //保存物流服务商信息
    $(document).on('click', '#saveChannelDiy', function() {
        var diyName = $('#channelDiyName').val();
        var channelId = $('#editLogisticsServiceId').val();
        if(diyName.length<=0){
            alert('自定义名称不能为空！');
            $('#channelDiyName').focus();
            return false
        }else{
            if(channelId == 'None'){
                alert('无效的物流服务商！');
                return false
            }
            var data = {diyName:diyName,channelId:channelId}
            $.getJSON('/erp/api/saveSmtLogisticsChanel/',data=data,function(result){
                if(result.success){
                    alert('保存成功！');
                }
            });
        }
    });


    $(document).on('click', '.channelSettings', function() {
        var channelName = $(this).attr('data-serviceName');
        var channelId = $(this).attr('data-val');
        $('#logisticsChannelSetingsId').val(channelId);
        $('#modal-channelSettings .modal-title span').html('[ '+channelName+' ]');
        $.getJSON('/erp/api/getYWLogisticsChanelInfo/?q='+channelId,function(data){
            if(data.total_count>0){
                if(data.result['diyName'] != 'None'){
                    $('#channelDiyName').val(data.result['diyName']);
                }else{
                    $('#channelDiyName').val('');
                }
                if(data.result['maxDeclareAmount'] != 'None'){
                    $('#maxDeclareAmount').val(data.result['maxDeclareAmount']);
                }else{
                    $('#maxDeclareAmount').val('');
                }
                if(data.result['printStyle'] != 'None'){
                    $('#printStyle').val(data.result['printStyle']);
                }else{
                    $('#printStyle').val('None');
                }

            }
        });

        $('#modal-channelSettings').modal('show');
    });
    //保存物流承运商信息
    $(document).on('click', '#saveYWChannel', function() {
        var diyName = $('#channelDiyName').val();
        var channelId = $('#logisticsChannelSetingsId').val();
        var maxDeclareAmount = $('#maxDeclareAmount').val();
        var printStyle = $('#printStyle').val();

            if(channelId == 'None'){
                alert('无效的物流服务商！');
                return false
            }
            var data = {diyName:diyName,channelId:channelId,maxDeclareAmount:maxDeclareAmount,printStyle:printStyle}
            $.getJSON('/erp/api/saveYWLogisticsChanel/',data=data,function(result){
                if(result.success){
                    alert('保存成功！');
                }
            });

    });

    //物流设置切换
    $(document).on('change', '#selectChannelType', function() {
        var currentPath = window.location.pathname;
        var smtPath = '/erp/smtLogisticsChannelSettings/';
        var ywPath = '/erp/yanwenLogisticsChannelSettings/';
        var type = $(this).val();
        if(type == '2'){
            if(currentPath != smtPath){
                location.href = smtPath;
            }
        }else if(type == '1'){
            if(currentPath != ywPath){
                location.href = ywPath;
            }
        }
    });


    $(document).on('click', '#todayview', function() {
      $('.fullcalendar').fullCalendar('today')
    });

})(jQuery);
